/**
 * 客户资源录入脚本支持
 */

/** 客户资源KEY * */
var clientKey = "";
var clientInvalid = false;
var modifydata = null;
var defState = null;

//页面载入初始化
$( "body" ).ready( function( e )
{
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}

	// 键盘事件
	$( "body" ).bind( "keyup", bodyKeyupHandler );

	// 初始化
	button_bind();
	init_editors();
	client_detailed( $( "#tbl_client" ), false );

	// 默认需要选中的状态，由URL参数而来
	init_default_state();

	// 修改数据设置（用户资料）
	if( !empty( modifydata ) )
		setClientData( modifydata );
} );

//--------------------------------------------------------------------------
//
//	consultant_client_first.php
//
//--------------------------------------------------------------------------

var _state_detailed = false;
var _editor = [];

function button_bind()
{
	$( "#btn_detailed" ).click( function( e )
	{
		e.stopPropagation();

		var show = $( "#tbl_client" ).find( "tr[rel='hide']" ).eq( 0 ).visible();
		client_detailed( $( "#tbl_client" ), !show );
	} );

	$( "#btnSubmit" ).bind( "click", submit_form );

	$( "#btnAddState" ).click( function( e )
	{
		parent.adder.setCallback( submit_newstate );
		parent.adder.open( "添加新客户状态", "状态名称：", "<em><b>说明</b>：请尽量精简保持在5个汉字以内，并且不要重复添加相同的状态名称。</em>" );
	} );

	$( "#btnSelect" ).bind( "click", function()
	{
		parent.clienter.setCallback( clientSelectedHandler );
		parent.clienter.reset();
		parent.clienter.open();
	} );

	$( "a[id^='btnSearchTracking']" ).bind( "click", search_tracking );
	empty_tracking();
	
	// 弹出客户资料编辑窗口
	$( "#btnEditClient" ).click( edit_client );
}

function edit_client()
{
	if( empty( clientKey ) )
	{
		infopad.err( "请先指定目标客户，再编辑资料。" );
		return;
	}

	var url = "consultant_client.php?key=" + clientKey + "&close=true";
	var title = "完善客户资料";
	var id = "consultant_client" + clientKey;

	parent.create_model( url, title, id, 8999, edit_client_closeHandler );
	parent.open_model( id );
}

function edit_client_closeHandler()
{
	// 刷新客户资料
	if( clientKey != null )
	{
		request_client_info( clientKey );
	}
}

function request_client_info( key )
{
	submitter.post( "client_info_get.php", {
		key: key
	}, function( d )
	{
		if( d.err == 0 )
		{
			clientSelectedHandler( d );
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}

function init_default_state()
{
	if( !empty( defState ) )
	{
		var states = defState.split( "," );

		$( "#statelist :checkbox" ).each( function( idx )
		{
			if( states.indexOf( $( this ).val() ) != -1 )
				$( this ).prop( "checked", true );
		} );
	}
}

function init_editors()
{
	$( "div[contenteditable='true']" ).each( function()
	{
		_editor.push( $( this ).attr( "id" ) );
	} );
}

function client_detailed( tar, visible )
{
	if( visible )
		tar.find( "tr[rel='hide']" ).show();
	else
		tar.find( "tr[rel='hide']" ).hide();

	setTableRowBackColor( tar );
}

//--------------------------------------------------------------------------
//
//	数据提交
//
//--------------------------------------------------------------------------

function search_tracking()
{
	if( check_target() == false )
		return;

	submitter.post( "client_tracking_search.php", {
		key: clientKey
	}, function( d )
	{
		var v = null;

		// 任何情况先隐藏可能已经显示的转交选择项目
		set_target_visible( $( "#givetarget" ), false );
		set_target_visible( $( "#date_target" ), false );

		if( d.today )
		{
			v = d.today;

			$( "#remark" ).html( v.remark );
			$( "#statelist :checkbox" ).each( function()
			{
				$( this ).prop( "checked", v.state.indexOf( $( this ).val() ) != -1 );

				if( $( this ).val() == "o3dpi9gzuol4" && v.state.indexOf( $( this ).val() ) != -1 )
				{
					set_target_visible( $( "#givetarget" ), true );
					$( "#giveto" ).val( v.giveto );
				}

				if( $( this ).val() == "138g5wfwm1mx" && v.state.indexOf( $( this ).val() ) != -1 )
				{
					set_target_visible( $( "#date_target" ), true );
					$( "#remind_date" ).val( v.remind_date );
				}
			} );
		}
		else
		{
			$( "#remark" ).html( "" );
			$( "#statelist :checkbox" ).each( function()
			{
				$( this ).prop( "checked", false );
			} );
		}

		// 默认需要选中的状态，由URL参数而来
		init_default_state();

		if( d.err == 0 && d.size > 0 )
		{
			$( "a[id='btnSearchTracking2']" ).unbind( "click" );

			var h = "<ul>";

			for( var i = 0; i < d.size; i++ )
			{
				v = d[ i ];
				h += "<li>";
				h += "<p class=\"trackingtitle\">第 " + ( i + 1 ) + " 次跟踪记录<em class=\"caption\">（负责人："
						+ v.nickname + "　日期：" + v.mdatens + "）</em><a class='btnHidden'>点击隐藏</a></p>";
				h += "<p class=\"trackingstate\"><b>客户状态</b><span>";

				if( !empty( v.statens ) )
				{
					var ss = v.statens.split( "," );
					for( var j = 0; j < ss.length; j++ )
					{
						h += "<a class=\"stateitem\">" + ss[ j ] + "</a>";
					}

					// 若存在计划跟踪日期，则添加提醒
					if( v.state.indexOf( "138g5wfwm1mx" ) != -1 )
					{
						h += "<a class=\"rect quote\">计划跟踪日期：" + v.remind_date + "</a>";
					}
				}
				else
				{
					h += "<a class=\"stateitem caption\">无变化</a>";
				}

				h += "</span></p>";
				h += "<p><b>备注情况</b></p>";
				h += "<div class=\"content\">" + v.remark + "</div>";
				h += "</li>";
			}

			h += "</ul>";
			$( ".trackinglst" ).html( h );
			$( ".btnHidden" ).click( trackingtitleClickHandler );
			$( ".btnHidden" ).trigger( "click" );
		}
		else
		{
			empty_tracking();
			infopad.warn( "未查询到相关的历史跟踪记录。" );
		}
	}, "json" );
}

function trackingtitleClickHandler( e )
{
	if( $( this ).text() == "点击隐藏" )
	{
		$( this ).text( "点击展开" );
		var $p = $( this ).parent();
		$( this ).parent().parent().children().hide();
		$p.show();
	}
	else
	{
		$( this ).text( "点击隐藏" );
		$( this ).parent().parent().children().show();
	}
}

function empty_tracking()
{
	var h = "<p class=\"caption\">暂无记录，请尝试“<a id=\"btnSearchTracking2\">查询历史跟踪记录</a>”，查询结果仅供参考和比对。</p>";
	$( ".trackinglst" ).html( h );
	$( "a[id='btnSearchTracking2']" ).bind( "click", search_tracking );
}

function submit_newstate( arr )
{
	submitter.post( "consultant_state_add_go.php", {
		name: arr[ 0 ],
		explain: arr[ 1 ]
	}, function( d )
	{
		if( d.err == 0 )
		{
			infopad.msg( d.msg );

			$( "#statelist" )
					.append(
							"<label for='state_" + d.id + "' title='" + d.explain + "'><input id='state_"
									+ d.id + "' type='checkbox' value='" + d.key + "' checked='true'>"
									+ d.name + "</label>" );
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}

function check_target()
{
	// 检测是否已经设置有目标客户
	if( empty( clientKey ) )
	{
		infopad.err( "请先搜索选定要跟踪的目标客户。" );
		return false;
	}

	return true;
}

function submit_form()
{
	if( check_target() == false )
		return;

	// 检测是否为无效客户资源
	if( clientInvalid )
	{
		infopad.err( "所选择的客户为无效资源，不需要跟踪。" );
		return;
	}

	var data = {};

	// 客户资料
	data.key = clientKey;

	// 跟踪数据
	data.states = "";
	data.remark = htmlfilter( $( "#remark" ).html() );
	data.giveto = $( "#giveto" ).val();
	data.remind_date = $( "#remind_date" ).val();

	var states = [];

	$( "#statelist input:checked" ).each( function()
	{
		var val = $( this ).attr( "value" );
		states.push( val );
	} );
	data.states = states.join( "," );

	if( ( data.remark == "" || data.remark == "无" ) && data.invalid == 0 )
	{
		infopad.err( "跟踪备注信息必须填写。" );
		return;
	}

	submitter.post( "consultant_client_tracking_go.php", data, function( d )
	{
		if( d.err == 0 )
		{
			infopad.msg( d.msg );

			if( d.type == "give" )
				location.reload();
		}
		else
		{
			infopad.err( d.msg, d.delay );
		}
	}, "json" );
}

//--------------------------------------------------------------------------
//
//	methods
//
//--------------------------------------------------------------------------

function bodyKeyupHandler( e )
{
	if( e.ctrlKey && e.which == 13 )
	{
		submit_form();
	}
	else if( e.ctrlKey && e.shiftKey && e.which == 70 )// ctrl+shift+f
	{
		var edt = $( document.activeElement );
		var id = edt.attr( "id" );

		if( _editor.indexOf( id ) > -1 )
		{
			edt.html( htmlfilter( edt.html() ) );
		}
	}
}

function clientSelectedHandler( data )
{
	if( empty( data ) )
		return;

	setClientData( data );
}

function setClientData( data )
{
	// 客户资料
	if( typeof ( data ) == "object" && data.nickname )
	{
		if( empty( data.client ) )
			clientKey = data.key;
		else
			clientKey = data.client;
		
		// 查询历史跟踪记录
		search_tracking();
		
		$( "#btnSelectBox" ).hide();

		$( "#nickname" ).html(
				data.nickname
						+ ( data.invalid == 1 ? "<em class='caption'>（无效客户）</em>"
								: "<em class='valid'>（有效客户）</em>" ) );
		$( "#category" ).html( shtml( data.categoryns ) );
		$( "#source" ).html( shtml( data.sourcens ) );
		$( "#keyword" ).html( shtml( data.keyword ) );

		var address = data.province + " " + data.city + " （" + data.address + "）";
		$( "#address" ).html( empty( address ) ? "<em class='caption'>未填写</em>" : address );

		$( "#phone" ).html( shtml( data.phone ) );
		$( "#email" ).html( shtml( data.email ) );
		$( "#qq" ).html( shtml( data.qq ) );
		$( "#ip" ).html( shtml( data.ip ) );
		$( "#desc" ).html( shtml( data.desc ) );

		// 设置问卷地址列表
		quest_init( $( "#quest_list" ), $.parseJSON( data.quests ), true );
	}
	else
	{
		clientKey = null;
		
		$( "#btnSelectBox" ).show();
		
		// 清空历史跟踪记录
		empty_tracking();

		$( "#nickname" ).html( "&nbsp;" );
		$( "#category" ).html( "&nbsp;" );
		$( "#source" ).html( "&nbsp;" );
		$( "#address" ).html( "&nbsp;" );
		$( "#keyword" ).html( "&nbsp;" );
		$( "#address" ).html( "&nbsp;" );
		$( "#phone" ).html( "&nbsp;" );
		$( "#email" ).html( "&nbsp;" );
		$( "#qq" ).html( "&nbsp;" );
		$( "#ip" ).html( "&nbsp;" );
		$( "#desc" ).html( "&nbsp;" );

		$( "#quest_list" ).html( "&nbsp;" );
	}
}

function shtml( val )
{
	if( empty( val ) )
		return "<em class='caption'>未填写</em>";
	else if( val == '--' )
		return "<em class='caption'>禁止查看</em>";
	return val;
}

function contact_type( phone, email, qq )
{
	info = '';

	if( phone != "" || typeof ( phone ) != "undefined" )
	{
		info += "<em class='caption'>电话：</em>" + phone;
	}
	if( email != "" || typeof ( email ) != "undefined" )
	{
		info += "<em class='caption'> - 邮箱：</em>" + email;
	}
	if( qq != "" || typeof ( qq ) != "undefined" )
	{
		info += "<em class='caption'> - QQ：</em>" + qq;
	}
	return info;
}
